package com.situ.orderingsystem.servlet;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson2.JSON;
import com.situ.orderingsystem.model.Employee;
import com.situ.orderingsystem.model.EmployeeSerchBean;
import com.situ.orderingsystem.model.Order;
import com.situ.orderingsystem.model.OrderSearchBean;
import com.situ.orderingsystem.service.EmpoloyeeService;
import com.situ.orderingsystem.service.OrderService;
import com.situ.orderingsystem.service.impl.EmployeeServiceImpl;
import com.situ.orderingsystem.service.impl.OrderServiceImpl;
import com.situ.orderingsystem.utils.BeanFactory;
import com.situ.orderingsystem.utils.PaginateInfo;
import com.situ.orderingsystem.utils.Servlets;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@WebServlet("/order/*")
public class OrderServlet extends HttpServlet {
    private final OrderService service = BeanFactory.getBean(OrderServiceImpl.class);
    private HttpServletResponse resp;
    private HttpServletRequest req;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String url = req.getRequestURI();
        String context = req.getContextPath();
        String action = url.replace(context, "");
        if (action.equals("/order/list")) {
            req.getRequestDispatcher("/WEB-INF/jsp/order/list.jsp").forward(req, resp);
        } else if (action.equals("/order/add")) {
            HttpSession session =req.getSession();
            Order order =(Order)session.getAttribute("order");
            String error = (String)session.getAttribute("error");
            if(order != null){
                req.setAttribute("order",order);
                session.removeAttribute("order");
                req.setAttribute("error",error);
                session.removeAttribute("error");
            }
            req.getRequestDispatcher("/WEB-INF/jsp/order/add.jsp").forward(req, resp);
        }else  if(action.equals("/order/edit")){
            String id = req.getParameter("id");
            try{
                Order emp = service.searchById(Integer.parseInt(id));
                emp.setId(Integer.parseInt(id));

                if(emp == null){
                    req.setAttribute("error","你要修改的顾客不存在");
                }
                else{
                    req.setAttribute("order",emp);
                }
            }catch (NumberFormatException e) {
                req.setAttribute("error", "请指定要修改的学生的编号");
            }
            req.getRequestDispatcher("/WEB-INF/jsp/order/edit.jsp").forward(req,resp);
        }
        else if(action.equals("/order/export")){
            export();
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.resp = resp;
        this.req = req;
        String url = req.getRequestURI();
        String context = req.getContextPath();
        String action = url.replace(context, "");
        if (action.equals("/order/list")) {
            search();

        } else if (action.equals("/order/delete")) {
            delete();
        } else if (action.equals("/order/add")) {
            save();
        }else  if(action.equals("/order/edit")){
            edit();
        }


    }

    private void search() {
        String pageNo = req.getParameter("pageNo");
        String pageSize = req.getParameter("pageSize");
        String empId = req.getParameter("empId");
        String ordId = req.getParameter("ordId");
        String foodId = req.getParameter("foodId");

        OrderSearchBean osb = new OrderSearchBean();
        if (StringUtils.hasText(empId)) {
            osb.setEmpId(empId);
        }
        if (StringUtils.hasText(ordId)) {
            osb.setOrdId(ordId);
        }
        if (StringUtils.hasText(foodId)) {
            osb.setFoodId(foodId);
        }
        int iPageNo = 1;
        if (StringUtils.hasText(pageNo)) {
            iPageNo = Integer.parseInt(pageNo);
        }
        int iPageSize = 10;
        if (StringUtils.hasText(pageSize)) {
            iPageSize = Integer.parseInt(pageSize);
        }
//            从数据库中查询
        PaginateInfo pi = new PaginateInfo(iPageNo, iPageSize);
        List<Order> elist = service.findAll(osb, pi);
        //响应ajax
        String json = JSON.toJSONString(Map.of("elist", elist, "pi", pi));
        Servlets.renderJson(json, resp);
    }

    private void delete() {
        String[] strIds = req.getParameterValues("ids");
        Integer[] ids = Stream.of(strIds).map(Integer::valueOf).toArray(Integer[]::new);
        for(Integer i:ids){
            System.out.println(i);
        }
        try {
            int rows = service.deleteByIds(ids);
            Servlets.renderJson(Map.of("success", true, "msg", "删除成功", "rows", rows), resp);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("============");
            Servlets.renderJson(Map.of("success", false, "error", "删除失败"), resp);
        }

    }

    private void save() throws IOException {
//        System.out.println(id+"===========");
        String empId = req.getParameter("emp_id");
        String ordId = req.getParameter("ord_id");
        String foodId = req.getParameter("food_id");
        HttpSession session = req.getSession();

        boolean passed = true;
        List<String> errors = new ArrayList<>();

        //校验
        Order order = new Order();
        if (!StringUtils.hasText(empId)) {
            Servlets.renderJson(Map.of("error", "编号不可为空"), resp);
            return;
        }

        order.setEmpId(empId);
        if (!StringUtils.hasText(ordId)) {
            Servlets.renderJson(Map.of("error", "编号不可为空"), resp);
            return;
        }
        order.setOrdId(ordId);
        if (!StringUtils.hasText(foodId)) {
            Servlets.renderJson(Map.of("error", "电话不可为空"), resp);
            return;
        }
        order.setFoodId(foodId);


        if (!passed) {
            session.setAttribute("order", order);
            String error = errors.stream().collect(Collectors.joining(","));
            session.setAttribute("error", error);
            resp.sendRedirect(req.getContextPath()+"/order/add");
            return;
        }
        boolean sava = service.save(order);

        if(sava){
            resp.sendRedirect(req.getContextPath()+"/order/list");
        }else{
            session.setAttribute("order",order);
            session.setAttribute("error","保存顾客信息失败");
            resp.sendRedirect(req.getContextPath()+"/order/add");
        }
    }
    private void edit(){
        String id = req.getParameter("empId");
        System.out.println(id+"===========");
        String empId = req.getParameter("emp_id");
        String ordId = req.getParameter("ord_id");
        String foodId = req.getParameter("food_id");
        HttpSession session = req.getSession();

        //校验
        Order order = new Order();
        if (!StringUtils.hasText(id)) {
            Servlets.renderJson(Map.of("error", "要修改的学生编号不可为空"), resp);
            return;
        }
        try {
            order.setId(Integer.valueOf(id));
        }catch (NumberFormatException e) {
            Servlets.renderJson(Map.of("error", "要修改的学生编号不正确"), resp);
            return;
        }

        if (!StringUtils.hasText(empId)) {
            Servlets.renderJson(Map.of("error", "编号不可为空"), resp);
            return;
        }

        order.setEmpId(empId);
        if (!StringUtils.hasText(ordId)) {
            Servlets.renderJson(Map.of("error", "编号不可为空"), resp);
            return;
        }
        order.setOrdId(ordId);
        if (!StringUtils.hasText(foodId)) {
            Servlets.renderJson(Map.of("error", "电话不可为空"), resp);
            return;
        }
        order.setFoodId(foodId);
//        System.out.println(order.toString());
        boolean b = service.update(order);
        System.out.println(b);
        if(b){
            Servlets.renderJson(Map.of("success",true),resp);
        }
        else {
            Servlets.renderJson(Map.of("success",false,"error","保存学生信息失败"),resp);

        }



    }
    private void export(){
        List<Order> elist = service.findAll();
        resp.setContentType("application/vnd.ms-excel");

        resp.setCharacterEncoding("utf-8");

        try{
            LocalDateTime now = LocalDateTime.now();
            String format = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
            String fileName = URLEncoder.encode("订单列表导出" + format, "UTF-8").replaceAll("\\+", "%20");
            resp.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            //导出
            EasyExcel.write(resp.getOutputStream(), Employee.class).sheet("模板").doWrite(elist );

        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}
